#include "udpserver.h"
#include "ui_udpserver.h"
#include <QVariant>
UdpServer::UdpServer(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::UdpServer)
{
    ui->setupUi(this);
    serverudp=new QUdpSocket(this);
    serverudp->bind(5000,QUdpSocket::ShareAddress);//绑定读数据端口(监听端口)，允许其他服务绑定到此端口
    connect(serverudp,SIGNAL(readyRead()),this,SLOT(recv()));
}

UdpServer::~UdpServer()
{
    delete ui;
}
void UdpServer::recv()
{
    while(serverudp->hasPendingDatagrams())
    {
        QByteArray data;
        data.resize(serverudp->pendingDatagramSize());
        serverudp->readDatagram(data.data(),data.size());//
        ui->textEdit_show->clear();
        ui->textEdit_show->setText(QVariant(data).toString());
    }
}

void UdpServer::on_pushButton_clicked()
{
    //    QHostAddress serverip;
    //    serverip.setAddress(QString("192.168.0.7"));//这是人为指定ip地址的方法
    serverudp->writeDatagram(QVariant(ui->textEdit_write->toPlainText()).toByteArray(),QHostAddress::LocalHost,6000);//向6000端口写数据
}
//注意，监听与发送的端口可以相同也可以不同，它们相对独立，就像有名管道
